#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include "drv_common_def.h"
#include "drv_serial_port.h"
#include "drv_led.h"

#define LOG_MAX_LEN 128
void Log_Output(const char *funcName, int lineNum, const char *fmt, ...)
{
    char buff[LOG_MAX_LEN] = {0};
    sprintf(buff, "%s:%d ", funcName, lineNum);
    uint8_t pos = strlen(buff);
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(buff + pos, LOG_MAX_LEN - pos, fmt, ap);
    va_end(ap);
    SerialPort *debugUart = GetDebugSerialPort();
    debugUart->write(debugUart, buff, strlen(buff));
}

#define HUNDRED_MILLION 100000000LLU
char *U64ToString(const uint64_t num, char *numStr, size_t arrLen)
{
    assert(arrLen >= 21);
    uint64_t var = num;
    uint32_t varArr[3] = {0};
    varArr[2] = (uint32_t)(var % HUNDRED_MILLION);
    var /= HUNDRED_MILLION;
    varArr[1] = (uint32_t)(var % HUNDRED_MILLION);
    var /= HUNDRED_MILLION;
    varArr[0] = (uint32_t)(var % HUNDRED_MILLION);
    int len = 0;
    uint8_t zero = 0;

    for (int i = 0; i < 3; i++) {
        if (zero) {
            sprintf(numStr + len, "%08lu", varArr[i]);
        } else if (varArr[i] != 0) {
            sprintf(numStr + len, "%lu", varArr[i]);
            zero = 1;
        }
        len = strlen(numStr);
    }
    return numStr;
}

#define MILLION_NUM 1000000
char *Float64ToString(const double num, char *numStr, size_t arrLen)
{
    assert(numStr != NULL);
    int32_t integer = (int32_t)num;
    int32_t decimalNum = (num - integer) * MILLION_NUM;
    assert(arrLen >= 21);
    sprintf(numStr, "%ld.%06ld", integer, decimalNum);
    return numStr;
}

